package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.common.BaseContext;
import com.example.common.R;
import com.example.until.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 是否登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // 路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println(IpUtil.getIpAddr(request)+"********************************");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1，获取uri
        String requestURI = request.getRequestURI();
        log.info("拦截到请求路径: {}", requestURI);
        // 放行路径
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/front/**"
        };
        // 2、判断是否需要处理
        boolean check = check(uris, requestURI);
        // 3、不要拦截放行
        if (check) {
            log.info("忽略请求路径: {}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        // 4-1、判断登录，登录则放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("已登录: 用户ID：{}", request.getSession().getAttribute("employee"));

            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);

            filterChain.doFilter(request, response);
            return;
        }
        // 4-2、移动端判断登录，登录则放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("移动端已登录: 用户ID：{}", request.getSession().getAttribute("user"));

            Long userid = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userid);

            filterChain.doFilter(request, response);
            return;
        }

        // 5、判断登录，未登录拦截
        log.info("未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
        // filterChain.doFilter(request, response);
        // return;

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param requestURI
     * @return
     */
    public boolean check(String[] uris, String requestURI) {
        for (String s : uris) {
            boolean match = PATH_MATCHER.match(s, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

}
